/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.bank.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.bank.entity.*;
import org.springblade.modules.bank.service.*;
import org.springblade.modules.bank.vo.TmVisitTaskVO;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务变更申请 控制器
 *
 * @author Blade
 * @since 2022-07-08
 */
@RestController
//@AllArgsConstructor
@RequestMapping("/tmVisitTaskChange")
@Api(value = "任务变更申请", tags = "任务变更申请接口")
public class TmVisitTaskChangeController extends BladeController {
    @Autowired
    private ITmVisitTaskChangeService tmVisitTaskChangeService;

    @Autowired
    private ITmVisitTaskCustomerChangeService tmVisitTaskCustomerChangeService;

    @Autowired
    private ITmVisitTaskService tmVisitTaskService;

    @Autowired
    private ITmVisitTaskCustomerService tmVisitTaskCustomerService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITmCustomerService customerService;

    @Autowired
    private IDeptService deptService;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 分页 任务申请变更
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入tmVisitTaskChange")
    public R<IPage<TmVisitTaskChange>> list(TmVisitTaskChange tmVisitTaskChange, Query query) {
        BladeUser bladeUser = SecureUtil.getUser();
        LambdaQueryWrapper<TmVisitTaskChange> queryWrapper = Condition.getQueryWrapper(tmVisitTaskChange).lambda();;
        if (null != tmVisitTaskChange.getChargeDateBegin() && null != tmVisitTaskChange.getChargeDateEnd()) {
            queryWrapper.between(TmVisitTaskChange::getChargeDate, tmVisitTaskChange.getChargeDateBegin(), tmVisitTaskChange.getChargeDateEnd());
        }
        //部门权限过滤
        if(null != tmVisitTaskChange.getDeptId() && !"".equals(tmVisitTaskChange.getDeptId())){
            queryWrapper.in(TmVisitTaskChange::getDeptId,tmVisitTaskChange.getDeptId());
        }
//        else {
//            User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getId, bladeUser.getUserId()));
//            LambdaQueryWrapper<Dept> queryDept=new QueryWrapper<Dept>().lambda();
//            queryDept.eq(Dept::getTenantId,"000000");
//            queryDept.and(wrapper -> wrapper.eq(Dept::getId,one.getDeptId()).or().like(Dept::getAncestors,one.getDeptId()));
//            List<Dept> list = deptService.list(queryDept);
//            List<String> depts = new ArrayList<>();
//            list.forEach(dept -> {
//                depts.add(String.valueOf(dept.getId()));
//            });
//            queryWrapper.in(TmVisitTaskChange::getDeptId,depts);
//        }
        if ("apply".equals(tmVisitTaskChange.getPageName())) { //申请
            if (null != tmVisitTaskChange.getTaskStatus() && !"".equals(tmVisitTaskChange.getTaskStatus())) {
                queryWrapper.eq(TmVisitTaskChange::getTaskStatus, tmVisitTaskChange.getTaskStatus());
            } else {
                queryWrapper.in(TmVisitTaskChange::getTaskStatus, "1", "2", "3", "4");
            }
        } else { //审核
            if (null != tmVisitTaskChange.getTaskStatus() && !"".equals(tmVisitTaskChange.getTaskStatus())) {
                queryWrapper.eq(TmVisitTaskChange::getTaskStatus, tmVisitTaskChange.getTaskStatus());
            } else {
                queryWrapper.in(TmVisitTaskChange::getTaskStatus, "2", "4");
            }
            if (tmVisitTaskChange.getDataPermission()!=null){
                if (tmVisitTaskChange.getDataPermission()==1){}
                else if(tmVisitTaskChange.getDataPermission()==2){
                    List<Dept> deptList = deptService.list(new LambdaQueryWrapper<Dept>().eq(Dept::getParentId,tmVisitTaskChange.getQueryParentDeptId()));
                    List<Long> deptIdList = deptList.stream().map(item->item.getId()).collect(Collectors.toList());
                    if (deptIdList.size()==0){
                        return R.data(null);
                    }
                    queryWrapper.in(TmVisitTaskChange::getDeptId,deptIdList);
                }else if(tmVisitTaskChange.getDataPermission()==3){
                    queryWrapper.eq(TmVisitTaskChange::getDeptId,tmVisitTaskChange.getQueryDeptId());
                }
            }
        }
        queryWrapper.orderByDesc(TmVisitTaskChange::getChargeDate);
        IPage<TmVisitTaskChange> pages = tmVisitTaskChangeService.page(Condition.getPage(query), queryWrapper);
        return R.data(pages);
    }

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入tmVisitTaskChange")
    public R<TmVisitTaskChange> detail(TmVisitTaskChange tmVisitTaskChange) {
        TmVisitTaskChange detail = tmVisitTaskChangeService.getOne(Condition.getQueryWrapper(tmVisitTaskChange));
        return R.data(detail);
    }


    /**
     * 新增 拜访任务
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入tmVisitTaskChange")
    public R save(@Valid @RequestBody TmVisitTaskChange tmVisitTaskChange) {
        return R.status(tmVisitTaskChangeService.save(tmVisitTaskChange));
    }

    /**
     * 修改 拜访任务
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入tmVisitTaskChange")
    public R update(@Valid @RequestBody TmVisitTaskChange tmVisitTaskChange) {
        return R.status(tmVisitTaskChangeService.updateById(tmVisitTaskChange));
    }

    /**
     * 新增或修改 任务变更申请
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入tmVisitTaskChange")
    public R submit(@Valid @RequestBody TmVisitTaskChange tmVisitTaskChange) {
        String option = "add";
        BladeUser bladeUser = SecureUtil.getUser();
        if (null == tmVisitTaskChange.getId()) {
            tmVisitTaskChange.setCreateBy(bladeUser.getUserId());
            tmVisitTaskChange.setChargeDate(LocalDate.now());
            tmVisitTaskChange.setChargeUserId(bladeUser.getUserId());
            tmVisitTaskChange.setChargeUserName(bladeUser.getUserName());
            tmVisitTaskChange.setTaskType("1");
//            TmVisitTask tmVisitTask = tmVisitTaskService.getById(tmVisitTaskChange.getTaskId());
//            tmVisitTaskChange.setChangeTaskName(tmVisitTask.getTaskName());
            boolean save = tmVisitTaskChangeService.save(tmVisitTaskChange);
            //根据taskId 获取申请数据客户数据
            if (save) {
                List<TmVisitTaskCustomer> tmVisitTaskCustomers = tmVisitTaskCustomerService.list(new QueryWrapper<TmVisitTaskCustomer>().lambda()
                        .eq(TmVisitTaskCustomer::getTaskId, tmVisitTaskChange.getTaskId())
                        .eq(TmVisitTaskCustomer::getVisitStatus, 0));
                List<TmVisitTaskCustomerChange> addList = new ArrayList<>();
                tmVisitTaskCustomers.forEach(cus -> {
                    TmVisitTaskCustomerChange customerChange = new TmVisitTaskCustomerChange();
                    customerChange.setChangeTaskId(tmVisitTaskChange.getId());
                    customerChange.setTaskCustomerId(String.valueOf(cus.getId()));
                    customerChange.setTaskCode(tmVisitTaskChange.getTaskCode());
                    customerChange.setDeptId(Long.valueOf(tmVisitTaskChange.getDeptId()));
                    customerChange.setDeptName(tmVisitTaskChange.getDeptName());
                    customerChange.setCustMgr(cus.getCustMgr());
                    customerChange.setCustMgrName(cus.getCustMgrName());
                    customerChange.setCustomerCode(cus.getCustomerCode());
                    customerChange.setCustomerPhone(cus.getCustomerPhone());
                    customerChange.setSex(cus.getSex());
                    customerChange.setCreateBy(bladeUser.getUserId());
                    addList.add(customerChange);
                });
                tmVisitTaskCustomerChangeService.saveBatch(addList);
            }
        } else {
            //修改主表数据
            if ("1".equals(tmVisitTaskChange.getTaskStatus())) {
                boolean save = tmVisitTaskChangeService.updateById(tmVisitTaskChange);
                //先删除子表所有数据再进行保存
//                tmVisitTaskCustomerChangeService.remove(new QueryWrapper<TmVisitTaskCustomerChange>().lambda().eq(TmVisitTaskCustomerChange::getChangeTaskId, tmVisitTaskChange.getId()));
//                if (save) {
//                    List<TmVisitTaskCustomer> tmVisitTaskCustomers = tmVisitTaskCustomerService.list(new QueryWrapper<TmVisitTaskCustomer>().lambda()
//                            .eq(TmVisitTaskCustomer::getTaskId, tmVisitTaskChange.getTaskId())
//                            .eq(TmVisitTaskCustomer::getVisitStatus, 0));
//                    List<TmVisitTaskCustomerChange> addList = new ArrayList<>();
//                    tmVisitTaskCustomers.forEach(cus -> {
//                        TmVisitTaskCustomerChange customerChange = new TmVisitTaskCustomerChange();
//                        customerChange.setChangeTaskId(tmVisitTaskChange.getId());
//                        customerChange.setTaskCustomerId(String.valueOf(cus.getId()));
//                        customerChange.setTaskCode(tmVisitTaskChange.getTaskCode());
//                        customerChange.setDeptId(Long.valueOf(tmVisitTaskChange.getDeptId()));
//                        customerChange.setDeptName(tmVisitTaskChange.getDeptName());
//                        customerChange.setCustMgr(cus.getCustMgr());
//                        customerChange.setCustMgrName(cus.getCustMgrName());
//                        customerChange.setCustomerCode(cus.getCustomerCode());
//                        customerChange.setCustomerPhone(cus.getCustomerPhone());
//                        customerChange.setSex(cus.getSex());
//                        customerChange.setCreateBy(bladeUser.getUserId());
//                        addList.add(customerChange);
//                    });
//                    tmVisitTaskCustomerChangeService.saveBatch(addList);
//                }
            }
            tmVisitTaskChange.setUpdateBy(bladeUser.getUserId());
            long count = tmVisitTaskCustomerChangeService.count(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                    .eq(TmVisitTaskCustomerChange::getChangeTaskId, tmVisitTaskChange.getId()));
            tmVisitTaskChange.setCustNumber((int) count);
//            //审批记录
//            if ("4".equals(tmVisitTaskChange.getTaskStatus())) {
//                option = "audit";
//                tmVisitTaskChange.setAuditUserId(bladeUser.getUserId());
//                tmVisitTaskChange.setAuditUserName(bladeUser.getUserName());
//                tmVisitTaskChange.setAuditTime(LocalDateTime.now());
//            }
        }
        long count = tmVisitTaskCustomerChangeService.count(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                .eq(TmVisitTaskCustomerChange::getChangeTaskId, tmVisitTaskChange.getId()));
        tmVisitTaskChange.setCustNumber((int) count);
        boolean b = tmVisitTaskChangeService.saveOrUpdate(tmVisitTaskChange);
        return R.data(tmVisitTaskChange);

    }

    /**
     * 作废 拜访任务
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑作废", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids, String taskStatus) {
        if ("3".equals(taskStatus)) {
            //驳回作废需要去更新tm_visit_task_customer表状态=3的修改成0
            List<TmVisitTaskCustomerChange> list = tmVisitTaskCustomerChangeService.list(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                    .in(TmVisitTaskCustomerChange::getChangeTaskId, Func.toLongList(ids)));
            List<String> customerId = new ArrayList<>();
            for (TmVisitTaskCustomerChange customerChange : list) {
                customerId.add(customerChange.getTaskCustomerId());
            }
            tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                    .in(TmVisitTaskCustomer::getId, customerId).eq(TmVisitTaskCustomer::getVisitStatus, "3")
                    .set(TmVisitTaskCustomer::getVisitStatus, "0"));
        }
//		先删除子表数据，再删除主表数据；
        tmVisitTaskCustomerChangeService.remove(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                .in(TmVisitTaskCustomerChange::getChangeTaskId, Func.toLongList(ids)));
        return R.status(tmVisitTaskChangeService.removeByIds(Func.toLongList(ids)));
    }

    /**
     * 查询今天已有的任务数
     *
     * @return
     */
    @GetMapping("/getNewTaskNum")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "查询今天已有的任务数", notes = "无需传参")
    public long getNewTaskNum() {
        LambdaQueryWrapper<TmVisitTaskChange> queryWrapper = new QueryWrapper<TmVisitTaskChange>().lambda().eq(TmVisitTaskChange::getChargeDate, LocalDate.now());
        long count = tmVisitTaskChangeService.count(queryWrapper);
        return count;
    }

    /**
     * 根据部门id查询当前部门可变更的任务
     */
    @GetMapping("/getCanChangeTaskList")
    @ApiOperation(value = "根据部门id查询当前部门可变更的任务", notes = "传入部门id")
    public List<TmVisitTaskVO> getCanChangeTaskList(@RequestParam String deptId) {
        List<TmVisitTaskVO> tmVisitTaskList = tmVisitTaskService.getCanChangeTaskList(deptId);
        return tmVisitTaskList;
    }

    @PostMapping("/rowSubmits")
    @ApiOperation(value = "变更申请提交、审核方法", notes = "传入部门id")
    public R rowSubmits(@ApiParam(value = "变更申请提交、审核方法", required = true) @RequestParam String id, String option) {
        BladeUser bladeUser = SecureUtil.getUser();
        LambdaUpdateWrapper<TmVisitTaskChange> updateWrapper = new UpdateWrapper<TmVisitTaskChange>().lambda();
        updateWrapper.set(TmVisitTaskChange::getTaskStatus, option);
        if("2".equals(option)){ //提交操作
            //更新tm_visit_task_customer表对应任务和客户经理字段的客户visit_status=3，且visit_status<>’1’，细表调整为字段为空的不更新，且从细表中把该数据删除。
            updateWrapper.eq(TmVisitTaskChange::getId, id);
            List<TmVisitTaskCustomerChange> list = tmVisitTaskCustomerChangeService.getEligibleData(id);
            List<String> cusId = new ArrayList<>();
            List<String> changeCusId = new ArrayList<>();
            if(list.size()>0){
                list.forEach(item -> {
                    cusId.add(item.getTaskCustomerId());
                    changeCusId.add(item.getId());
                });
                tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                        .set(TmVisitTaskCustomer::getVisitStatus,3)
                        .in(TmVisitTaskCustomer::getId,cusId));
                tmVisitTaskCustomerChangeService.remove(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                        .notIn(TmVisitTaskCustomerChange::getId,changeCusId)
                        .eq(TmVisitTaskCustomerChange::getChangeTaskId,id));
            }else {
                return R.fail("没有需要调整的拜访客户，请检查！");
            }
        }
        if ("4".equals(option)) {
            updateWrapper.set(TmVisitTaskChange::getAuditUserId, bladeUser.getUserId());
            updateWrapper.set(TmVisitTaskChange::getAuditUserName, bladeUser.getUserName());
            updateWrapper.set(TmVisitTaskChange::getAuditTime, LocalDateTime.now());
            List<Long> longs = Func.toLongList(id);
            updateWrapper.in(TmVisitTaskChange::getId,longs);
            longs.forEach(mainId -> {
                //  更新主表状态为已审核，更新主表审核人、审核日期，
                //  同步更新tm_visit_task_customer表该客户属于对应任务、客户经理字段、“调整为”有客户经理，且拜访状态=’3’中visit_status=’0’和新的客户经理。
                List<TmVisitTaskCustomerChange> changeList = tmVisitTaskCustomerChangeService.list(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                        .eq(TmVisitTaskCustomerChange::getChangeTaskId, mainId));
                changeList.forEach(item -> {
                    tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                            .set(TmVisitTaskCustomer::getVisitStatus,0)
                            .set(TmVisitTaskCustomer::getCustMgr,item.getCustMgrChange())
                            .set(TmVisitTaskCustomer::getCustMgrName,item.getCustMgrNameChange())
                            .set(TmVisitTaskCustomer::getUpdateBy,bladeUser.getUserId())
                            .set(TmVisitTaskCustomer::getUpdateTime, LocalDateTime.now())
                            .eq(TmVisitTaskCustomer::getVisitStatus,3)
                            .eq(TmVisitTaskCustomer::getId,item.getTaskCustomerId()));
                });
            });
        }
        boolean update = tmVisitTaskChangeService.update(updateWrapper);
        return R.success("执行成功");
    }

    /**
     * 任务变更申请驳回
     */
    @PostMapping("/rejected")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "任务变更申请驳回", notes = "传入id")
    public R rejected(@ApiParam(value = "主键集合", required = true) @RequestParam String id, String reason) {
        BladeUser bladeUser = SecureUtil.getUser();
        LambdaUpdateWrapper<TmVisitTaskChange> updateWrapper = new UpdateWrapper<TmVisitTaskChange>().lambda();
        updateWrapper.set(TmVisitTaskChange::getRejectReason, reason);
        updateWrapper.set(TmVisitTaskChange::getAuditUserId, bladeUser.getUserId());
        updateWrapper.set(TmVisitTaskChange::getAuditUserName, bladeUser.getUserName());
        updateWrapper.set(TmVisitTaskChange::getAuditTime, LocalDateTime.now());
        updateWrapper.set(TmVisitTaskChange::getTaskStatus, "3");
        updateWrapper.eq(TmVisitTaskChange::getId, id);
        List<TmVisitTaskCustomerChange> changeList = tmVisitTaskCustomerChangeService.list(new QueryWrapper<TmVisitTaskCustomerChange>().lambda()
                .eq(TmVisitTaskCustomerChange::getChangeTaskId, id));
        changeList.forEach(item -> {
            tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                    .set(TmVisitTaskCustomer::getVisitStatus,0)
                    .set(TmVisitTaskCustomer::getUpdateBy,bladeUser.getUserId())
                    .set(TmVisitTaskCustomer::getUpdateTime, LocalDateTime.now())
                    .eq(TmVisitTaskCustomer::getVisitStatus,3)
                    .eq(TmVisitTaskCustomer::getId,item.getTaskCustomerId()));
        });
        tmVisitTaskChangeService.update(updateWrapper);
        return R.success("驳回成功");
    }
}
